/**
 * 大屏端显示界面逻辑
 * 处理画布显示、远程控制接收、自动隐藏界面等功能
 */

class DisplayScreen {
    constructor() {
        this.canvas = null;
        this.ctx = null;
        this.isFullscreen = false;
        this.hideTimer = null;
        this.hideDelay = 5000; // 5秒后自动隐藏界面元素
        this.fps = 0;
        this.frameCount = 0;
        this.lastFpsUpdate = Date.now();
        this.latency = 0;
        this.controllerCount = 0;

        // 画册模式相关属性
        this.currentMode = 'draw';
        this.galleryImages = [];
        this.currentImageIndex = 0;
        this.imageTransform = {
            x: 0,
            y: 0,
            scale: 1,
            rotation: 0
        };
        this.isDragging = false;
        this.lastTouchDistance = 0;
        this.lastTouchAngle = 0;

        this.init();
    }

    init() {
        this.setupCanvas();
        this.setupEventListeners();
        this.setupAutoHide();
        this.startTimeDisplay();
        this.startFpsCounter();
        this.updateConnectionStatus();
        this.generateQRCode();
    }

    /**
     * 设置画布
     */
    setupCanvas() {
        this.canvas = document.getElementById('sandbox-canvas');
        if (!this.canvas) return;

        this.ctx = this.canvas.getContext('2d');
        this.resizeCanvas();

        // 监听窗口大小变化
        window.addEventListener('resize', () => {
            this.resizeCanvas();
        });
    }

    /**
     * 调整画布大小
     */
    resizeCanvas() {
        if (!this.canvas) return;

        const container = this.canvas.parentElement;
        const rect = container.getBoundingClientRect();

        // 设置画布实际大小
        this.canvas.width = rect.width * window.devicePixelRatio;
        this.canvas.height = rect.height * window.devicePixelRatio;

        // 设置画布显示大小
        this.canvas.style.width = rect.width + 'px';
        this.canvas.style.height = rect.height + 'px';

        // 缩放上下文以匹配设备像素比
        this.ctx.scale(window.devicePixelRatio, window.devicePixelRatio);

        // 更新分辨率显示
        const resolutionElement = document.getElementById('resolution');
        if (resolutionElement) {
            resolutionElement.textContent = `${rect.width}x${rect.height}`;
        }
    }

    /**
     * 设置事件监听器
     */
    setupEventListeners() {
        // 全屏按钮
        const fullscreenBtn = document.getElementById('fullscreen-btn');
        if (fullscreenBtn) {
            fullscreenBtn.addEventListener('click', () => this.toggleFullscreen());
        }

        // 设置按钮
        const settingsBtn = document.getElementById('settings-btn');
        if (settingsBtn) {
            settingsBtn.addEventListener('click', () => this.showSettings());
        }

        // 监听WebSocket消息
        window.addEventListener('websocket-message', (event) => {
            this.handleWebSocketMessage(event.detail);
        });

        window.addEventListener('websocket-connected', () => {
            this.onConnected();
        });

        window.addEventListener('websocket-disconnected', () => {
            this.onDisconnected();
        });

        // 监听用户交互事件以重置隐藏计时器
        const resetHideOnInteraction = () => {
            this.resetHideTimer();
        };

        document.addEventListener('mousemove', resetHideOnInteraction);
        document.addEventListener('mousedown', resetHideOnInteraction);
        document.addEventListener('click', resetHideOnInteraction);
        document.addEventListener('touchstart', resetHideOnInteraction);
        document.addEventListener('touchmove', resetHideOnInteraction);

        // 监听键盘事件
        document.addEventListener('keydown', (e) => {
            this.handleKeyboard(e);
            this.resetHideTimer(); // 键盘事件也重置计时器
        });

        // 监听全屏状态变化
        document.addEventListener('fullscreenchange', () => {
            this.isFullscreen = !!document.fullscreenElement;
            this.updateFullscreenButton();
        });

        // 监听设备方向变化
        window.addEventListener('deviceOrientationChange', (event) => {
            this.handleOrientationChange(event.detail);
        });
    }

    /**
     * 设置自动隐藏功能
     */
    setupAutoHide() {
        this.resetHideTimer();
    }

    /**
     * 重置隐藏计时器
     */
    resetHideTimer() {
        if (this.hideTimer) {
            clearTimeout(this.hideTimer);
        }

        this.showUIElements();

        this.hideTimer = setTimeout(() => {
            this.hideUIElements();
        }, this.hideDelay);
    }

    /**
     * 显示UI元素
     */
    showUIElements() {
        const elements = document.querySelectorAll('.auto-hide');
        elements.forEach(el => {
            el.classList.remove('fade-out');
        });

        // 确保二维码始终可见
        const qrCode = document.getElementById('qr-code');
        if (qrCode) {
            qrCode.classList.remove('fade-out');
        }
    }

    /**
     * 隐藏UI元素
     */
    hideUIElements() {
        const elements = document.querySelectorAll('.auto-hide');
        elements.forEach(el => {
            // 跳过二维码元素，让它一直显示
            if (el.id !== 'qr-code') {
                el.classList.add('fade-out');
            }
        });
    }

    /**
     * 开始时间显示
     */
    startTimeDisplay() {
        const updateTime = () => {
            const timeElement = document.getElementById('time-display');
            if (timeElement) {
                const now = new Date();
                timeElement.textContent = now.toLocaleTimeString();
            }
        };

        updateTime();
        setInterval(updateTime, 1000);
    }

    /**
     * 开始FPS计数器
     */
    startFpsCounter() {
        const updateFps = () => {
            this.frameCount++;
            const now = Date.now();

            if (now - this.lastFpsUpdate >= 1000) {
                this.fps = this.frameCount;
                this.frameCount = 0;
                this.lastFpsUpdate = now;

                const fpsElement = document.getElementById('fps');
                if (fpsElement) {
                    fpsElement.textContent = this.fps;
                }
            }

            requestAnimationFrame(updateFps);
        };

        requestAnimationFrame(updateFps);
    }

    /**
     * 处理WebSocket消息
     */
    handleWebSocketMessage(message) {
        const startTime = Date.now();

        switch (message.type) {
            case 'trackpad_event':
                this.handleTrackpadEvent(message);
                break;
            case 'multitouch_event':
                this.handleMultitouchEvent(message);
                break;
            case 'gallery_gesture':
                this.handleGalleryGesture(message);
                break;
            case 'tool_change':
                this.handleToolChange(message);
                break;
            case 'settings_update':
                this.handleSettingsUpdate(message);
                break;
            case 'clear_canvas':
                this.clearCanvas();
                break;
            case 'reset_view':
                this.resetView();
                break;
            case 'drawing_data':
                this.handleDrawingData(message);
                break;
            case 'controller_connected':
                this.controllerCount++;
                this.updateControllerCount();
                break;
            case 'controller_disconnected':
                this.controllerCount = Math.max(0, this.controllerCount - 1);
                this.updateControllerCount();
                break;
            case 'mode_change':
                this.handleModeChange(message);
                break;
            case 'image_share':
                this.handleImageShare(message);
                break;
            case 'clear_gallery':
                this.handleClearGallery(message);
                break;
            case 'gallery_navigate':
                this.handleGalleryNavigate(message);
                break;
        }

        // 计算延迟
        if (message.timestamp) {
            this.latency = Date.now() - message.timestamp;
            this.updateLatency();
        }
    }

    /**
     * 处理画册手势事件
     */
    handleGalleryGesture(message) {
        const { event, data } = message;

        // 只在画册模式下处理手势事件
        if (this.currentMode !== 'gallery') return;

        // 模拟触控事件来操作图片
        const canvasRect = this.canvas.getBoundingClientRect();
        const x = data.x * canvasRect.width;
        const y = data.y * canvasRect.height;

        switch (event) {
            case 'start':
                this.galleryTouchStart = {
                    x: x,
                    y: y,
                    timestamp: Date.now()
                };
                break;

            case 'move':
                if (this.galleryTouchStart && this.galleryImages.length > 0) {
                    const deltaX = x - this.galleryTouchStart.x;
                    const deltaY = y - this.galleryTouchStart.y;

                    // 更新图片位置
                    this.imageTransform.x += deltaX;
                    this.imageTransform.y += deltaY;

                    this.galleryTouchStart.x = x;
                    this.galleryTouchStart.y = y;

                    this.displayCurrentImage();
                }
                break;

            case 'end':
                this.galleryTouchStart = null;
                break;
        }
    }

    /**
     * 处理触控板事件
     */
    handleTrackpadEvent(message) {
        const { event, data } = message;
        const remoteCursor = document.getElementById('remote-cursor');

        if (!remoteCursor || !this.canvas) return;

        // 只在画笔模式下处理绘制事件
        if (this.currentMode === 'gallery') return;

        const rect = this.canvas.getBoundingClientRect();
        const x = data.x * rect.width;
        const y = data.y * rect.height;

        // 更新远程光标位置
        remoteCursor.style.left = x + 'px';
        remoteCursor.style.top = y + 'px';
        remoteCursor.style.display = 'block';

        // 显示绘制指示器
        if (event === 'start' || event === 'move') {
            this.showDrawingIndicator();

            // 在画布上绘制
            this.drawOnCanvas(x, y, data, event === 'start');
        } else if (event === 'end') {
            this.hideDrawingIndicator();

            // 隐藏远程光标
            setTimeout(() => {
                remoteCursor.style.display = 'none';
            }, 1000);
        }
    }

    /**
     * 处理多指触控事件
     */
    handleMultitouchEvent(message) {
        const { event, data } = message;

        // 只在画册模式下处理多指手势
        if (this.currentMode !== 'gallery') return;

        if (!this.galleryImages || this.galleryImages.length === 0) return;

        const rect = this.canvas.getBoundingClientRect();
        const centerX = data.centerX * rect.width;
        const centerY = data.centerY * rect.height;

        switch (event) {
            case 'multitouch_start':
                // 记录初始状态
                this.multitouchStart = {
                    scale: this.imageTransform.scale,
                    rotation: this.imageTransform.rotation,
                    x: this.imageTransform.x,
                    y: this.imageTransform.y
                };
                break;

            case 'multitouch_move':
                if (this.multitouchStart) {
                    // 应用缩放
                    if (data.scaleRatio && Math.abs(data.scaleRatio - 1) > 0.01) {
                        const newScale = this.imageTransform.scale * data.scaleRatio;
                        // 限制缩放范围
                        this.imageTransform.scale = Math.max(0.1, Math.min(5.0, newScale));
                    }

                    // 应用旋转 - 使用手机端发送的角度数据
                    if (data.angle !== undefined) {
                        // 直接使用手机端计算的两个手指连线角度（角度值）
                        console.log("rotate angle:", data.angle);
                        this.imageTransform.rotation = data.angle;

                        // 保持角度在 0 到 360 范围内
                        this.imageTransform.rotation = ((this.imageTransform.rotation % 360) + 360) % 360;
                    }

                    // 重新绘制图片
                    this.displayCurrentImage();
                }
                break;

            case 'multitouch_end':
                this.multitouchStart = null;
                break;
        }
    }

    /**
     * 在画布上绘制
     */
    drawOnCanvas(x, y, data, isStart) {
        if (!this.ctx) return;

        this.ctx.globalAlpha = data.opacity || 1;
        this.ctx.lineWidth = data.brushSize || 5;
        this.ctx.lineCap = 'round';
        this.ctx.lineJoin = 'round';

        // 根据工具类型设置绘制样式
        switch (data.tool) {
            case 'pen':
                this.ctx.globalCompositeOperation = 'source-over';
                this.ctx.strokeStyle = '#000000';
                break;
            case 'eraser':
                this.ctx.globalCompositeOperation = 'destination-out';
                break;
            case 'building':
                this.ctx.globalCompositeOperation = 'source-over';
                this.ctx.strokeStyle = '#8B4513';
                break;
            case 'tree':
                this.ctx.globalCompositeOperation = 'source-over';
                this.ctx.strokeStyle = '#228B22';
                break;
            case 'road':
                this.ctx.globalCompositeOperation = 'source-over';
                this.ctx.strokeStyle = '#696969';
                break;
            case 'water':
                this.ctx.globalCompositeOperation = 'source-over';
                this.ctx.strokeStyle = '#4169E1';
                break;
        }

        if (isStart) {
            this.ctx.beginPath();
            this.ctx.moveTo(x, y);
        } else {
            this.ctx.lineTo(x, y);
            this.ctx.stroke();
        }
    }

    /**
     * 处理工具变更
     */
    handleToolChange(message) {
        console.log('工具切换:', message.tool);
        // 可以在界面上显示当前工具
    }

    /**
     * 处理设置更新
     */
    handleSettingsUpdate(message) {
        console.log('设置更新:', message.settings);
        // 可以在界面上显示当前设置
    }

    /**
     * 处理绘制数据
     */
    handleDrawingData(message) {
        // 处理完整的绘制数据同步
        if (message.imageData && this.ctx) {
            const img = new Image();
            img.onload = () => {
                this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
                this.ctx.drawImage(img, 0, 0);
            };
            img.src = message.imageData;
        }
    }

    /**
     * 处理模式切换
     */
    handleModeChange(message) {
        this.currentMode = message.mode;

        if (message.mode === 'gallery') {
            this.switchToGalleryMode();
        } else if (message.mode === 'draw') {
            this.switchToDrawMode();
        }
    }

    /**
     * 处理图片分享
     */
    handleImageShare(message) {
        const imageInfo = {
            data: message.data,
            filename: message.filename,
            width: message.width,
            height: message.height,
            timestamp: message.timestamp
        };

        this.galleryImages.push(imageInfo);
        this.currentImageIndex = this.galleryImages.length - 1;

        if (this.currentMode === 'gallery') {
            this.displayCurrentImage();
        }

        this.showImageNotification(message.filename);
    }

    /**
     * 处理清空画册
     */
    handleClearGallery(message) {
        this.galleryImages = [];
        this.currentImageIndex = 0;
        this.resetImageTransform();

        if (this.currentMode === 'gallery') {
            this.clearCanvas();
        }

        this.showNotification('画册已清空');
    }

    /**
     * 处理画册导航
     */
    handleGalleryNavigate(message) {
        if (this.currentMode !== 'gallery') return;

        if (message.action === 'previous') {
            this.previousImage();
        } else if (message.action === 'next') {
            this.nextImage();
        }
    }

    /**
     * 切换到画册模式
     */
    switchToGalleryMode() {
        this.clearCanvas();
        this.setupGalleryControls();

        if (this.galleryImages.length > 0) {
            this.displayCurrentImage();
        } else {
            this.showGalleryPlaceholder();
        }
    }

    /**
     * 切换到绘制模式
     */
    switchToDrawMode() {
        this.hideGalleryControls();
        this.clearCanvas();
    }

    /**
     * 设置画册控制界面
     */
    setupGalleryControls() {
        // 创建画册控制界面
        let galleryControls = document.getElementById('gallery-controls');
        if (!galleryControls) {
            galleryControls = document.createElement('div');
            galleryControls.id = 'gallery-controls';
            galleryControls.className = 'gallery-controls';
            galleryControls.innerHTML = `
                <div class="gallery-info">
                    <span id="image-counter">0 / 0</span>
                    <span id="image-name">无图片</span>
                </div>
                <div class="gallery-buttons">
                    <button id="prev-image" class="gallery-btn">◀ 上一张</button>
                    <button id="next-image" class="gallery-btn">下一张 ▶</button>
                    <button id="reset-transform" class="gallery-btn">🔄 重置</button>
                </div>
            `;

            document.body.appendChild(galleryControls);

            // 添加样式
            const style = document.createElement('style');
            style.textContent = `
                .gallery-controls {
                    position: fixed;
                    bottom: 20px;
                    left: 50%;
                    transform: translateX(-50%);
                    background: rgba(0, 0, 0, 0.8);
                    color: white;
                    padding: 15px;
                    border-radius: 10px;
                    display: flex;
                    flex-direction: column;
                    gap: 10px;
                    z-index: 1000;
                }
                .gallery-info {
                    text-align: center;
                    font-size: 14px;
                }
                .gallery-buttons {
                    display: flex;
                    gap: 10px;
                }
                .gallery-btn {
                    padding: 8px 12px;
                    background: #007bff;
                    color: white;
                    border: none;
                    border-radius: 5px;
                    cursor: pointer;
                    font-size: 12px;
                }
                .gallery-btn:hover {
                    background: #0056b3;
                }
                .gallery-btn:disabled {
                    background: #6c757d;
                    cursor: not-allowed;
                }
            `;

            document.head.appendChild(style);
        }

        // 绑定事件
        document.getElementById('prev-image').onclick = () => this.previousImage();
        document.getElementById('next-image').onclick = () => this.nextImage();
        document.getElementById('reset-transform').onclick = () => this.resetImageTransform();

        // 设置触控事件
        this.setupGalleryTouchEvents();

        galleryControls.style.display = 'flex';
        this.updateGalleryInfo();
    }

    /**
     * 隐藏画册控制界面
     */
    hideGalleryControls() {
        const galleryControls = document.getElementById('gallery-controls');
        if (galleryControls) {
            galleryControls.style.display = 'none';
        }
    }

    /**
     * 显示当前图片
     */
    displayCurrentImage() {
        if (this.galleryImages.length === 0 || !this.ctx) return;

        const imageInfo = this.galleryImages[this.currentImageIndex];
        if (!imageInfo) return;

        const img = new Image();
        img.onload = () => {
            this.clearCanvas();
            this.drawImageWithTransform(img);
            this.updateGalleryInfo();
        };

        img.src = imageInfo.data;
    }

    /**
     * 绘制带变换的图片
     */
    drawImageWithTransform(img) {
        const ctx = this.ctx;
        const canvas = this.canvas;

        ctx.save();

        // 移动到画布中心
        ctx.translate(canvas.width / 2, canvas.height / 2);

        // 应用用户变换
        ctx.translate(this.imageTransform.x, this.imageTransform.y);
        ctx.scale(this.imageTransform.scale, this.imageTransform.scale);
        ctx.rotate(this.imageTransform.rotation * Math.PI / 180);

        // 计算图片显示尺寸（保持宽高比）
        const maxWidth = canvas.width * 0.8;
        const maxHeight = canvas.height * 0.8;
        const scale = Math.min(maxWidth / img.width, maxHeight / img.height);

        const displayWidth = img.width * scale;
        const displayHeight = img.height * scale;

        // 绘制图片（以中心为原点）
        ctx.drawImage(img, -displayWidth / 2, -displayHeight / 2, displayWidth, displayHeight);

        ctx.restore();
    }

    /**
     * 设置画册触控事件
     */
    setupGalleryTouchEvents() {
        if (!this.canvas) return;

        let touches = [];

        // 触摸开始
        this.canvas.addEventListener('touchstart', (e) => {
            e.preventDefault();
            touches = Array.from(e.touches);

            if (touches.length === 1) {
                this.isDragging = true;
            } else if (touches.length === 2) {
                this.isDragging = false;
                this.lastTouchDistance = this.getTouchDistance(touches[0], touches[1]);
                this.lastTouchAngle = this.getTouchAngle(touches[0], touches[1]);
            }
        });

        // 触摸移动
        this.canvas.addEventListener('touchmove', (e) => {
            e.preventDefault();
            const currentTouches = Array.from(e.touches);

            if (currentTouches.length === 1 && this.isDragging) {
                // 单指拖拽
                const deltaX = currentTouches[0].clientX - touches[0].clientX;
                const deltaY = currentTouches[0].clientY - touches[0].clientY;

                this.imageTransform.x += deltaX;
                this.imageTransform.y += deltaY;

                this.displayCurrentImage();
            } else if (currentTouches.length === 2) {
                // 双指缩放和旋转
                const currentDistance = this.getTouchDistance(currentTouches[0], currentTouches[1]);
                const currentAngle = this.getTouchAngle(currentTouches[0], currentTouches[1]);

                // 缩放
                const scaleChange = currentDistance / this.lastTouchDistance;
                this.imageTransform.scale *= scaleChange;
                this.imageTransform.scale = Math.max(0.1, Math.min(5, this.imageTransform.scale));

                // 旋转 - 处理角度跨越边界的情况
                let angleChange = currentAngle - this.lastTouchAngle;

                // 处理角度跨越 -π 到 π 边界的情况
                if (angleChange > Math.PI) {
                    angleChange -= 2 * Math.PI;
                } else if (angleChange < -Math.PI) {
                    angleChange += 2 * Math.PI;
                }

                // 应用旋转变化
                this.imageTransform.rotation += angleChange;

                // 保持角度在 0 到 2π 范围内
                this.imageTransform.rotation = ((this.imageTransform.rotation % (2 * Math.PI)) + 2 * Math.PI) % (2 * Math.PI);

                this.lastTouchDistance = currentDistance;
                this.lastTouchAngle = currentAngle;

                this.displayCurrentImage();
            }

            touches = currentTouches;
        });

        // 触摸结束
        this.canvas.addEventListener('touchend', (e) => {
            e.preventDefault();
            this.isDragging = false;
            touches = Array.from(e.touches);
        });

        // 鼠标事件（用于桌面测试）
        let isMouseDown = false;
        let lastMouseX = 0;
        let lastMouseY = 0;

        this.canvas.addEventListener('mousedown', (e) => {
            if (this.currentMode !== 'gallery') return;
            isMouseDown = true;
            lastMouseX = e.clientX;
            lastMouseY = e.clientY;
        });

        this.canvas.addEventListener('mousemove', (e) => {
            if (this.currentMode !== 'gallery' || !isMouseDown) return;

            const deltaX = e.clientX - lastMouseX;
            const deltaY = e.clientY - lastMouseY;

            this.imageTransform.x += deltaX;
            this.imageTransform.y += deltaY;

            this.displayCurrentImage();

            lastMouseX = e.clientX;
            lastMouseY = e.clientY;
        });

        this.canvas.addEventListener('mouseup', () => {
            isMouseDown = false;
        });

        // 鼠标滚轮缩放
        this.canvas.addEventListener('wheel', (e) => {
            if (this.currentMode !== 'gallery') return;
            e.preventDefault();

            const scaleChange = e.deltaY > 0 ? 0.9 : 1.1;
            this.imageTransform.scale *= scaleChange;
            this.imageTransform.scale = Math.max(0.1, Math.min(5, this.imageTransform.scale));

            this.displayCurrentImage();
        });
    }

    /**
     * 获取两点间距离
     */
    getTouchDistance(touch1, touch2) {
        const dx = touch1.clientX - touch2.clientX;
        const dy = touch1.clientY - touch2.clientY;
        return Math.sqrt(dx * dx + dy * dy);
    }

    /**
     * 获取两点间角度（弧度）
     */
    getTouchAngle(touch1, touch2) {
        const dx = touch2.clientX - touch1.clientX;
        const dy = touch2.clientY - touch1.clientY;
        return Math.atan2(dy, dx);
    }

    /**
     * 上一张图片
     */
    previousImage() {
        if (this.galleryImages.length === 0) return;

        this.currentImageIndex = (this.currentImageIndex - 1 + this.galleryImages.length) % this.galleryImages.length;
        this.resetImageTransform();
        this.displayCurrentImage();
    }

    /**
     * 下一张图片
     */
    nextImage() {
        if (this.galleryImages.length === 0) return;

        this.currentImageIndex = (this.currentImageIndex + 1) % this.galleryImages.length;
        this.resetImageTransform();
        this.displayCurrentImage();
    }

    /**
     * 重置图片变换
     */
    resetImageTransform() {
        this.imageTransform = {
            x: 0,
            y: 0,
            scale: 1,
            rotation: 0
        };

        if (this.currentMode === 'gallery') {
            this.displayCurrentImage();
        }
    }

    /**
     * 更新画册信息显示
     */
    updateGalleryInfo() {
        const counter = document.getElementById('image-counter');
        const nameSpan = document.getElementById('image-name');
        const prevBtn = document.getElementById('prev-image');
        const nextBtn = document.getElementById('next-image');

        if (counter) {
            counter.textContent = `${this.currentImageIndex + 1} / ${this.galleryImages.length}`;
        }

        if (nameSpan) {
            const currentImage = this.galleryImages[this.currentImageIndex];
            nameSpan.textContent = currentImage ? currentImage.filename : '无图片';
        }

        if (prevBtn) {
            prevBtn.disabled = this.galleryImages.length <= 1;
        }

        if (nextBtn) {
            nextBtn.disabled = this.galleryImages.length <= 1;
        }
    }

    /**
     * 显示画册占位符
     */
    showGalleryPlaceholder() {
        if (!this.ctx) return;

        this.clearCanvas();

        const ctx = this.ctx;
        const canvas = this.canvas;

        ctx.save();
        ctx.fillStyle = '#f8f9fa';
        ctx.fillRect(0, 0, canvas.width, canvas.height);

        ctx.fillStyle = '#6c757d';
        ctx.font = '24px Arial';
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';

        ctx.fillText('📷', canvas.width / 2, canvas.height / 2 - 30);
        ctx.font = '18px Arial';
        ctx.fillText('暂无图片', canvas.width / 2, canvas.height / 2 + 10);
        ctx.font = '14px Arial';
        ctx.fillText('请使用手机分享图片到大屏', canvas.width / 2, canvas.height / 2 + 35);

        ctx.restore();
    }

    /**
     * 显示图片通知
     */
    showImageNotification(filename) {
        this.showNotification(`收到图片: ${filename}`);
    }

    /**
     * 显示通知
     */
    showNotification(message) {
        // 创建通知元素
        const notification = document.createElement('div');
        notification.className = 'image-notification';
        notification.textContent = message;

        // 添加样式
        notification.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            background: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 10px 15px;
            border-radius: 5px;
            font-size: 14px;
            z-index: 10000;
            animation: slideIn 0.3s ease-out;
        `;

        // 添加动画样式
        if (!document.getElementById('notification-style')) {
            const style = document.createElement('style');
            style.id = 'notification-style';
            style.textContent = `
                @keyframes slideIn {
                    from { transform: translateX(100%); opacity: 0; }
                    to { transform: translateX(0); opacity: 1; }
                }
                @keyframes slideOut {
                    from { transform: translateX(0); opacity: 1; }
                    to { transform: translateX(100%); opacity: 0; }
                }
            `;
            document.head.appendChild(style);
        }

        document.body.appendChild(notification);

        // 3秒后自动移除
        setTimeout(() => {
            notification.style.animation = 'slideOut 0.3s ease-in';
            setTimeout(() => {
                if (notification.parentNode) {
                    notification.parentNode.removeChild(notification);
                }
            }, 300);
        }, 3000);
    }

    /**
     * 清空画布
     */
    clearCanvas() {
        if (this.ctx) {
            this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
        }
    }

    /**
     * 重置视图
     */
    resetView() {
        this.resizeCanvas();
        console.log('视图已重置');
    }

    /**
     * 显示绘制指示器
     */
    showDrawingIndicator() {
        const indicator = document.getElementById('drawing-indicator');
        if (indicator) {
            indicator.classList.add('active');
        }
    }

    /**
     * 隐藏绘制指示器
     */
    hideDrawingIndicator() {
        const indicator = document.getElementById('drawing-indicator');
        if (indicator) {
            indicator.classList.remove('active');
        }
    }

    /**
     * 切换全屏模式
     */
    toggleFullscreen() {
        if (!document.fullscreenElement) {
            document.documentElement.requestFullscreen();
        } else {
            document.exitFullscreen();
        }
    }

    /**
     * 更新全屏按钮
     */
    updateFullscreenButton() {
        const btn = document.getElementById('fullscreen-btn');
        if (btn) {
            btn.textContent = this.isFullscreen ? '⛶' : '⛶';
            btn.title = this.isFullscreen ? '退出全屏' : '全屏模式';
        }
    }

    /**
     * 显示设置
     */
    showSettings() {
        // 创建设置面板
        const settings = document.createElement('div');
        settings.style.cssText = `
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: rgba(0, 0, 0, 0.9);
            color: white;
            padding: 30px;
            border-radius: 15px;
            z-index: 1000;
            min-width: 300px;
        `;

        settings.innerHTML = `
            <h3 style="margin-bottom: 20px;">显示设置</h3>
            <div style="margin-bottom: 15px;">
                <label>自动隐藏延迟: </label>
                <input type="range" min="1" max="10" value="${this.hideDelay / 1000}" id="hide-delay-slider">
                <span id="hide-delay-value">${this.hideDelay / 1000}秒</span>
            </div>
            <div style="text-align: center; margin-top: 20px;">
                <button onclick="this.parentElement.parentElement.remove()" style="padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer;">关闭</button>
            </div>
        `;

        document.body.appendChild(settings);

        // 设置滑块事件
        const slider = settings.querySelector('#hide-delay-slider');
        const valueSpan = settings.querySelector('#hide-delay-value');

        slider.addEventListener('input', (e) => {
            this.hideDelay = parseInt(e.target.value) * 1000;
            valueSpan.textContent = e.target.value + '秒';
        });
    }

    /**
     * 处理键盘事件
     */
    handleKeyboard(e) {
        switch (e.key) {
            case 'F11':
                e.preventDefault();
                this.toggleFullscreen();
                break;
            case 'Escape':
                if (this.isFullscreen) {
                    document.exitFullscreen();
                }
                break;
            case ' ':
                e.preventDefault();
                this.resetHideTimer();
                break;
        }
    }

    /**
     * 处理设备方向变化
     */
    handleOrientationChange(detail) {
        setTimeout(() => {
            this.resizeCanvas();
        }, 100);
    }

    /**
     * 连接成功回调
     */
    onConnected() {
        const statusIndicator = document.getElementById('status-indicator');
        const statusText = document.getElementById('status-text');
        const connectionStatus = document.getElementById('connection-status');

        if (statusIndicator) statusIndicator.classList.add('connected');
        if (statusText) statusText.textContent = '已连接';
        if (connectionStatus) connectionStatus.classList.add('hidden');
    }

    /**
     * 断开连接回调
     */
    onDisconnected() {
        const statusIndicator = document.getElementById('status-indicator');
        const statusText = document.getElementById('status-text');
        const connectionStatus = document.getElementById('connection-status');

        if (statusIndicator) statusIndicator.classList.remove('connected');
        if (statusText) statusText.textContent = '未连接';
        if (connectionStatus) connectionStatus.classList.remove('hidden');
    }

    /**
     * 更新连接状态
     */
    updateConnectionStatus() {
        // 自动连接WebSocket
        if (window.websocketManager) {
            window.websocketManager.connect();
        }
    }

    /**
     * 更新延迟显示
     */
    updateLatency() {
        const latencyElement = document.getElementById('latency');
        if (latencyElement) {
            latencyElement.textContent = this.latency + 'ms';
        }
    }

    /**
     * 更新控制端数量
     */
    updateControllerCount() {
        const countElement = document.getElementById('controller-count');
        if (countElement) {
            countElement.textContent = this.controllerCount;
        }
    }

    /**
     * 生成二维码
     */
    async generateQRCode() {
        // 获取当前页面的协议
        const protocol = window.location.protocol;

        let hostname;
        try {
            // 动态获取服务器IP地址
            const response = await fetch('/api/server-ip');
            const data = await response.json();
            hostname = data.ip;
        } catch (error) {
            console.warn('获取服务器IP失败，使用当前主机地址:', error);
            // 如果获取失败，使用当前页面的主机地址
            hostname = window.location.hostname;
            // 如果是localhost，尝试使用常见的局域网IP
            if (hostname === 'localhost' || hostname === '127.0.0.1') {
                hostname = '192.168.1.3'; // 备用IP
            }
        }

        // 构建手机端访问URL
        const mobileUrl = `${protocol}//${hostname}:4000/mobile-control.html`;

        // 获取二维码容器
        const qrContainer = document.getElementById('qr-code');
        if (!qrContainer) return;

        // 清空原有内容
        qrContainer.innerHTML = '';

        try {
            // 检查QRCode库是否可用
            if (typeof QRCode !== 'undefined') {
                // 创建二维码容器div
                const qrDiv = document.createElement('div');
                qrDiv.style.cssText = 'margin-bottom: 10px;';

                // 使用qrcode.js库生成二维码
                new QRCode(qrDiv, {
                    text: mobileUrl,
                    width: 100,
                    height: 100,
                    colorDark: '#000000',
                    colorLight: '#ffffff',
                    correctLevel: QRCode.CorrectLevel.M
                });

                qrContainer.appendChild(qrDiv);

                // 添加说明文字
                const textDiv = document.createElement('div');
                textDiv.textContent = '扫码连接控制端';
                qrContainer.appendChild(textDiv);

                // 添加URL显示
                const urlDiv = document.createElement('div');
                urlDiv.style.cssText = 'font-size: 10px; margin-top: 5px; word-break: break-all;';
                urlDiv.textContent = mobileUrl;
                qrContainer.appendChild(urlDiv);

            } else {
                throw new Error('QRCode库未加载');
            }
        } catch (error) {
            console.error('二维码生成失败:', error);
            // 显示备用内容
            qrContainer.innerHTML = `
                <div style="width: 100px; height: 100px; background: #f0f0f0; margin-bottom: 10px; display: flex; align-items: center; justify-content: center; font-size: 12px; color: #666;">
                    📱 QR码
                </div>
                <div>扫码连接控制端</div>
                <div style="font-size: 10px; margin-top: 5px; word-break: break-all;">${mobileUrl}</div>
            `;
        }
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    window.displayScreen = new DisplayScreen();
});

// 导出供其他模块使用
if (typeof module !== 'undefined' && module.exports) {
    module.exports = DisplayScreen;
}